package com.anjie.powerproject.service.impl;

import com.anjie.powerproject.entity.DataDay;
import com.anjie.powerproject.entity.PreDataDay;
import com.anjie.powerproject.repository.DataDayRepository;
import com.anjie.powerproject.service.DataDayService;
import com.anjie.powerproject.strategy.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DataDayServiceImpl implements DataDayService {

    @Autowired
    DataDayRepository dataDayRepository;

    @Override
    public List<DataDay> getDataDayList(List<String> dateList, String devCode, Date startTime, Date endTime) {
        Date limitDate = DateUtils.plusOrMinusDay(endTime, 1).getTime();
        String start = DateUtils.ymdFormat.format(startTime);
        String end = DateUtils.ymdFormat.format(limitDate);

        List<DataDay> dataDayList = dataDayRepository.getDataDayList(devCode, start, end);
        Map<String, DataDay> dataDayMap = dataDayList.stream().collect(Collectors.toMap(e -> DateUtils.ymdFormat.format(e.getSdate()), e -> e, (e1, e2) -> e1));
        if (dateList != null) {
            List<DataDay> dataDays = new ArrayList<>();
            for (String date : dateList) {
                DataDay dataDay = dataDayMap.get(date);
                if (dataDay == null) {
                    dataDay = new DataDay();
                    dataDay.setData(BigDecimal.valueOf(0.0));
                }
                dataDays.add(dataDay);
            }
            return dataDays;
        }

        return dataDayList;
    }

    @Override
    public List<BigDecimal> getDataDayValues(List<String> dateList, String devCode, Date startTime, Date endTime) {
        Date limitDate = DateUtils.plusOrMinusDay(endTime, 1).getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String start = dateFormat.format(startTime);
        String end = dateFormat.format(limitDate);

        List<DataDay> dataDayList = dataDayRepository.getDataDayList(devCode, start, end);
        Map<String, BigDecimal> dataDayMap = dataDayList.stream().collect(Collectors.toMap(e -> dateFormat.format(e.getSdate()), DataDay::getData, (e1, e2) -> e1));
        if (dateList != null) {
            List<BigDecimal> dataDays = new ArrayList<>();
            for (String date : dateList) {
                BigDecimal val = dataDayMap.get(date);
                dataDays.add(val == null ? BigDecimal.valueOf(0.0) : val);
            }
            return dataDays;
        }

        return new ArrayList<>();
    }

    @Override
    public List<BigDecimal> getDataDayValues(String deviceCode, String startTime, String endTime){
        return dataDayRepository.getDataDayValues(deviceCode,startTime,endTime);
    }
}
